/*
 * @Author: 周鹏飞
 * @Date: 2021-06-08 09:08:23
 * @LastEditors: 周鹏飞
 * @LastEditTime: 2021-07-05 10:34:03
 * @Description: file content
 */
// 查询车辆

function getCarList() {
  $.ajax({
    type: 'post',
    url: httpUrl + 'vehicle/vehicleDevice/list',
    data: JSON.stringify({
      // "roadName": "内邓高速"
    }),
    dataType: 'json',
    contentType: "application/json",
    headers: {
      Authorization: localStorage.getItem('token')
    },
    success: function (res) {
      // 查询车辆列表
      vm.searchStatus = true
      vm.allList=res.data
      vm.defaultProps.label="vehiIdno"
      vm.Loading.close();
      if (res.code)
        console.log(res);
      if (res.code == 200) {
        $('.carText').css({ color: '#fe7272' })
        vm.$message({
          message: '车辆查询成功',
          type: 'success'
        });
        ClearLushu('CarPolicelushu')
        // ClearLushu('csxx')
        if (res.data.length != 0) {
          vm.polymerizationemphasisCarList = [];
          for (let [key, val] of Object.entries(res.data)) {
            // 位置
            let point = new BMap.Point(val.lng, val.lat)
            // 创建小车图标
            var myIcon = new BMap.Icon(imgUrl + val.logoUrl, new BMap.Size(50, 50));
            vm.map.centerAndZoom(new BMap.Point(111.989235, 32.790482), 11);
            var marker = new BMap.Marker(point, { icon: myIcon });
            // map.addOverlay(marker);    
            // 覆盖物标识
            marker.init = 'car'
            vm.map.addOverlay(marker)
            marker.setTop({ isTop: true })
            var content = `
            <div id="carBox"  style="    ">
            <div style="width: 100px; padding: 10px 0; margin: 10px 0; background: red; border-radius: 0 25px 25px 0; color: #ffffff;">
              &nbsp&nbsp&nbsp&nbsp 车辆信息
            </div>
            <div id="carNumber" style="padding: 3px 10px;">
              车牌号: ${val.vehiIdno}
            </div>
            <div id="carTime" style="padding: 3px 10px;">
              时间: ${new Date(parseInt(val.tm)).toLocaleString().replace(/:\d{1,2}$/, ' ')}
            </div>
            <div id="carPosition" style="padding: 3px 10px;">
              位置:  ${val.pos}
            </div>
            <div style="padding: 3px 10px;">
            开始:            <input type="text" class="demo-input" placeholder="请选择开始时间" id="k${val.devIdno}">
          </div> 
            <div style="padding: 3px 10px;">
            结束: <input id="j${val.devIdno}"placeholder="请选择结束时间" style="width: 170px;" type="text" value="" >
            </div>
      
            <div id="functions" >
            <div id="video">视频</div>
              <div id="trajectory" onclick='jectory(this,"${val.logoUrl}")' username=${val.devIdno} style=''> 
                轨迹 
              </div>
              <div id="call">通话</div>
           
            </div>
          </div>
           
            `
            addClickHandler(content, marker, 'car', val.devIdno,point) // 监控信息窗口
            // 标签创建
            var name = `
                <div class='carNumber' style='width: auto; height: 22px; padding: 2px 5px; line-height: 22px; text-align: center;'>
                  ${val.vehiIdno} ${val.online == 1 ? "在线" : "离线"}
                </div>`
            var Distance = val.vehiIdno.length * 8
            var opts = {
              position: point,    // 指定文本标注所在的地理位置
              offset: new BMap.Size(-Distance, 15)    //设置文本偏移量
            }
            let label = new BMap.Label(name, opts);  // 创建文本标注对象
            label.init = "car"
            label.setStyle({
              color: "#000",       //文本颜色
              fontSize: "14px",
              lineHeight: "24px",
              fontFamily: "微软雅黑",
              border: "0",
              borderRadius: '4px'
            });
            // 车辆信息聚合
            vm.polymerizationemphasisCarList.push(marker)

            //  鼠标移入显示标题
            vm.polymerizationemphasisCarList[key].addEventListener("mouseover", function (e) {
              vm.map.addOverlay(label);
            });
            // 鼠标移出把标题移除
            vm.polymerizationemphasisCarList[key].addEventListener("mouseout", function (e) {
              vm.map.removeOverlay(label);
            });


          }
          vm.polymerizationemphasisCar = new BMapLib.MarkerClusterer(vm.map, {
            markers: vm.polymerizationemphasisCarList,
            styles: [{
              url: './images/jk/carJh.png',
              size: new BMap.Size(36, 36),
              color: 'pink',
              textSize: 20,
              textColor: 'red'
            }]
          });
          // 设置最大缩放级别
          vm.polymerizationemphasisCar.setMaxZoom(11);
        }
      } else if (res.code == 500) {
        vm.$message({
          message: '查询失败请联系管理员',
          type: 'error'
        });
      }
    },
    error: function (err) {
      vm.$message({
        message: '查询失败请稍后再试',
        type: 'error'
      });
    }
  })
}

// 格式化时间
function jectory(e, img) {

  var imgurl = img
  console.log(e);
  // 警车号
  var username = $(e).attr('username')
  let data = {};
  data.name = username
  // 开始时间
  data.begin = ($('#k' + username).val());
  //  结束时间
  data.end = ($('#j' + username).val());
  if (data.begin == '') {
    vm.errork()
  }
  if (data.end == '') {
    vm.errorj()
  }
  console.log(data);
  this.getTrack(data, imgurl)
}

// 查询轨迹
function getTrack(data, imgurl) {
  $.ajax({
    type: "POST",
    url: httpUrl + "vehicle/vehicleDevice/track",
    dataType: "json",
    contentType: "application/json",
    headers: {
      Authorization: localStorage.getItem('token')
    },
    data: JSON.stringify({
      // 设备号
      devIdno: data.name,
      // 开始时间
      begintime: data.begin,
      // 结束时间
      endtime: data.end
    }),
    success: function (json) {
      if (json.rows.length > 4) {
        // 清除之前路书的信息
        ClearLushu('CarPolicelushu')
        ClearLushu('car')
        ClearLushu('peopleInfo')
        ClearLushu('peopleLushu')
        vm.model.peolushuPanel = false
        // 显示控制面板
        vm.model.lushuPanel = true
        var json = json.rows
        var p = Math.ceil(json.length / 2);
        // 根据中间数值显示地图中心点
        vm.map.centerAndZoom(new BMap.Point(json[p].lng, json[p].lat), 13);
        // 终点经纬度
        var jsonLast = json.length - 1;
        let points = [];
        // 循环获取数据
        for (var i = 0; i < json.length; i++) {
          var p = new BMap.Point(json[i].lng, json[i].lat);
          points.push(p);
        }
        // 让所有的点都在视图范围内
        vm.map.setViewport(points);
        // 画线 / (画轨迹图) points轨迹数据
        var polyline = new BMap.Polyline(points, {
          strokeColor: "#cdfdd0",// 设置颜色  
          strokeWeight: 6, // 宽度  
          strokeOpacity: 1, // 透明度 
          strokeStyle: "solid" // 设置是为实线或虚线，solid或dashed
        });
        polyline.init = "CarPolicelushu"
        vm.map.addOverlay(polyline);
        // 自定义消息窗口起点终点函数
        function Custom_messages() {
          // 起点终点
          addMarkers(new BMap.Point(json[0].lng, json[0].lat), "", 0, 0, new BMap.Icon('./images/q.png', new BMap.Size(25, 25)));
          addMarkers(new BMap.Point(json[jsonLast].lng, json[jsonLast].lat), "", 0, 0, new BMap.Icon("./images/z.png", new BMap.Size(25, 25)));

          /**
           * 标记点
           * @param {Object} point
           */
          function addMarkers(point, name, x, y, icon) {
            var marker = new BMap.Marker(point, { icon: icon });
            marker.init = "CarPolicelushu"
            vm.map.addOverlay(marker);
          }
        }
        Custom_messages()

        var landmarkPois = [];//路书经过点的信息(数组)
        // 循环获取数据
        for (var i = 0; i < json.length; i++) {
          // 路书信息
          landmarkPois.push(new landmark(
            Number(json[i].lng),
            Number(json[i].lat),
            `<p style="margin: 0; text-align: left">车牌号: ${json[i].vehiIdno}</p>`,

          ));
        }
        //路书经过点更改显示信息函数
        function landmark(lng, lat, html, ssTime) {

          this.lng = lng; // 经度
          this.lat = lat;	// 维度
          this.html = html; // 显示信息
          this.pauseTime = ssTime; //动画速度
        }
        // var marker = ;
        // marker.init = "csxx"
        // vm.map.addOverlay(marker);
        var lushu = new BMapLib.LuShu(vm.map, json, {
          defaultContent: '信息',
          autoView: false,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
          icon: new BMap.Icon(imgUrl + imgurl, new BMap.Size(52, 52), { anchor: new BMap.Size(27, 13) }), //小汽车图标
          speed: 10,
          enableRotation: false,//是否设置marker随着道路的走向进行旋转
          landmarkPois: landmarkPois
        });
        lushu.init = 'csxx'
        vm.map.addOverlay(lushu);

        // vm.map.addOverlay(lushu);

        //绑定事件
        $("run").onclick = function () {
          lushu.start();
        }
        $("stop").onclick = function () {
          lushu.stop();
        }
        $("pause").onclick = function () {
          lushu.pause();

        }
        $("deleteTrajectory").onclick = function () {
          ClearLushu('CarPolicelushu')
          vm.model.lushuPanel = false
          getCarList()
        }
        // 获取dom节点绑定到新节点上
        function $(element) {
          return document.getElementById(element);
        }
      } else {
        vm.$message({
          message: '暂无该车辆的轨迹信息',
          type: 'warning'
        });
      }

    },
    error: function (err) {
      vm.$message({
        message: '轨迹查询失败请稍后再试,或与管理员联系',
        type: 'error'
      });
    }
  })
}
